package com.autumn.platform.dao.schema.statement.original;

import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.ParameterMode;
import org.apache.ibatis.parsing.XNode;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import com.autumn.platform.dao.schema.parser.SchemaSqlMapperParserDelegate;
import com.autumn.platform.dao.schema.statement.StatementHandlerSupport;

public class ParameterMapStatementHandler extends StatementHandlerSupport {

    @Override
    public void handleStatementNode(Configuration configuration, SchemaSqlMapperParserDelegate delegate, XNode node) {
        MapperBuilderAssistant builder = delegate.getBuilderAssistant();
        String id = node.getStringAttribute("id");
        String type = node.getStringAttribute("type");
        Class<?> parameterClass = resolveClass(configuration, type);
        List<XNode> parameterNodes = node.evalNodes("parameter");
        List<ParameterMapping> parameterMappings = new ArrayList<ParameterMapping>();
        for (XNode parameterNode : parameterNodes) {
            String property = parameterNode.getStringAttribute("property");
            String javaType = parameterNode.getStringAttribute("javaType");
            String jdbcType = parameterNode.getStringAttribute("jdbcType");
            String resultMap = parameterNode.getStringAttribute("resultMap");
            String mode = parameterNode.getStringAttribute("mode");
            String typeHandler = parameterNode.getStringAttribute("typeHandler");
            Integer numericScale = parameterNode.getIntAttribute("numericScale");
            ParameterMode modeEnum = resolveParameterMode(mode);
            Class<?> javaTypeClass = resolveClass(configuration, javaType);
            JdbcType jdbcTypeEnum = resolveJdbcType(jdbcType);
            @SuppressWarnings("unchecked")
            Class<? extends TypeHandler<?>> typeHandlerClass = (Class<? extends TypeHandler<?>>) resolveClass(
                    configuration, typeHandler);
            ParameterMapping parameterMapping = builder.buildParameterMapping(parameterClass, property,
                    javaTypeClass, jdbcTypeEnum, resultMap, modeEnum, typeHandlerClass, numericScale);
            parameterMappings.add(parameterMapping);
        }
        builder.addParameterMap(id, parameterClass, parameterMappings);
    }
}
